﻿using System;
using System.Web;
using System.Web.UI;
using System.Text;
using System.Security.Cryptography;
using System.Data.SqlClient;
using System.Data;
using STP.Models;

namespace STP.Account
{
    public partial class Login : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void LogIn(object sender, EventArgs e)
        {
            if (IsValid)
            {
                string name = Name.Text;
                string password = Password.Text;
                byte[] result = Encoding.Default.GetBytes(password);
                MD5 md5 = new MD5CryptoServiceProvider();
                byte[] output = md5.ComputeHash(result);
                password = BitConverter.ToString(output).Replace("-", "");
                string sql = "select password,disable from users where name='" + name + "'";
                DB db = new DB();
                SqlDataReader read=db.ExceRead(sql);
                if(read.Read())
                {
                    if (password == read["password"].ToString().Trim())
                    {
                        if((bool)read["disable"]==true)
                        {
                            FailureText.Text = "用户已禁用";
                            ErrorMessage.Visible = true;
                            read.Close();
                            return;
                        }
                        //登陆成功
                        Session["user"] = name;
                        //返回页面
                        if(Session["returnUrl"]!=null)
                        {
                            string url = Session["returnUrl"].ToString().Trim();
                            Session["returnUrl"] = null;
                            Response.Redirect(url);
                        }
                        else
                        {
                            Response.Redirect("~/index.aspx");
                        }
                    }
                    else
                    {
                        FailureText.Text = "密码不正确";
                        ErrorMessage.Visible = true;
                    }
                }
                else
                {
                    FailureText.Text = "用户不存在";
                    ErrorMessage.Visible = true;
                }
                read.Close();
            }
        }
    }
}